package com.example.capsule_kafka.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.capsule_kafka.bean.GroupMessageBean;
import com.example.capsule_kafka.bean.RoomBean;
import com.example.capsule_kafka.mapper.GroupMessageMapper;
import com.example.capsule_kafka.mapper.RoomMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/4 20:35
 */
@Component
@Slf4j
public class messageSchedule {

    @Resource
    RoomMapper roomMapper;
    @Resource
    GroupMessageMapper groupMessageMapper;
    private static int preDelete = 0;

    //@Scheduled(cron = "0 0 3 ? * 1")
    //@Scheduled(cron = "0 0 4 15 * ?"),
    //@Scheduled(cron = "0 0 5 28 * ?"),

    @Scheduled(cron = "0 0 3 ? * 1")
    public void deleteGroupMessage() {

        int mark = preDelete == 0 ? 180 : Math.max(preDelete - 100, 0);
        preDelete = mark;
        QueryWrapper<RoomBean> queryWrapper = new QueryWrapper<RoomBean>().select("room_name");
        List<RoomBean> roomNameList = roomMapper.selectList(queryWrapper);
        CountDownLatch countDownLatch = new CountDownLatch(roomNameList.size());
        for (RoomBean roomBean : roomNameList) {
            countDownLatch.countDown();
            QueryWrapper<GroupMessageBean> wrapper = new QueryWrapper<GroupMessageBean>().eq("room_name", roomBean.getRoomName());
            List<GroupMessageBean> messageBeanList = groupMessageMapper.selectList(wrapper);
            int size = messageBeanList.size();
            int count = 0;
            if (messageBeanList.size() > mark) {
                while (size > mark) {
                    groupMessageMapper.deleteById(messageBeanList.get(count).getId());
                    size--;
                    count++;
                }
            }
        }
        try {
            countDownLatch.await();
            log.info("群聊消息长度检查完毕！");
        } catch (Exception e) {
            log.error("群聊消息长度检查出现异常------->  " + e);
        }
    }


}
